package com.yhx.demo;


import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

/**
 * 实现poi将数据写入excel
 */
public class POIDemo {
    public static void main(String[] args) throws IOException {
        //准备数据
        ArrayList<Student> list = new ArrayList<>();
        list.add(new Student(1,"jack",22));
        list.add(new Student(2,"tomer",33));
        list.add(new Student(3,"xixi",12));
        //创建一个工作簿
        XSSFWorkbook xssfSheets = new XSSFWorkbook();
        //创建一个工作表
        XSSFSheet sheet = xssfSheets.createSheet("学生数据");
        //创建一个行
        XSSFRow rowHeader = sheet.createRow(0);
        //行中又有单元格
        rowHeader.createCell(0).setCellValue("id");
        rowHeader.createCell(1).setCellValue("姓名");
        rowHeader.createCell(2).setCellValue("年龄");
        //将list中的数据存入excel中
        for (int i = 0; i < list.size(); i++) {
            XSSFRow row = sheet.createRow(i + 1);
            Student student = list.get(i);
            row.createCell(0).setCellValue(student.getId());
            row.createCell(1).setCellValue(student.getAge());
            row.createCell(2).setCellValue(student.getName());
        }
        //创建一个文件
        File file = new File("E:/upload/Excel/studentdata.xslx");
        //将文件写出
        xssfSheets.write(new FileOutputStream(file));
        //写出成功
        System.out.println("写出成功");
    }

}
